<template>
  <div>
    <Spin :spinning="exportLoading" tip="Loading...">
      <FormPanel ref="from" :list="formList" @formChange="changeHandle" :isSubmitBtn="false" :collapse="false" :labelWidth="190"></FormPanel>
      <FilterTable ref="table" :columns="columns" :dataSource="tableList" height="auto" :isSelectColumn="false" :onColumnsChange="(columns) => (this.columns = columns)">
        <!-- <template slot="controls" slot-scope="props"> -->
        <template slot="controls">
          <multiuse-button size="small" type="primary" @click="addHandle()" icon="el-icon-plus">新 增</multiuse-button>
        </template>
      </FilterTable>
      <BaseDialog :visible.sync="isaddCar" title="选择车辆" :width="'70%'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <addCar :rowData="rowData" :isClientOrder="isClientOrder" @close="carcloseHandler" />
      </BaseDialog>
      <BaseDialog :visible.sync="isDiscount" :title="'折扣详情'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <DiscountDetail :rowData="DiscountData" @close="Discountclose" />
      </BaseDialog>
      <div style="height: 47px"></div>
      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right',
        }"
      >
        <el-button @click="closeDrawer(1)">关 闭</el-button>
        <el-button @click="closeDrawer(2)" type="primary" :disabled="ischange">提 交</el-button>
        <el-button @click="closeDrawer(3)" type="primary" :disabled="ischange">保 存</el-button>
      </div>
    </Spin>
  </div>
</template>
<script>
import { getAmount, getDiscount, getDiscountDetails, saveOrder, getNotPage, getDealerAddress, getAllDiscount } from '@/api/dealerSale/OrderManagement/OrderSubmissionC';
import { dictionary } from '@/utils/dictMixin';
import Cookies from 'js-cookie';
import DiscountDetail from './DiscountDetail';
import addCar from './addCar';
import moment from 'moment';
export default {
  props: ['rowData', 'isClientOrder'],
  data() {
    this.saveData = null;
    this.Amount = null;

    return {
      formList: this.createdFrom(),
      columns: this.createdTable(),
      tableList: [],
      isaddCar: false,
      // rowData: {},
      json: {},
      isDiscount: false,
      DiscountData: {},
      TotalAmount: '',
      cache: {},
      exportLoading: false,
      dealerCode: Cookies.get('ownerCode'),
      ischange: false,
      rate: 0.5,
      addressDTO: [],
      realPayTotalAmount: 0.0, //订单总金额
      singleRebateFuelAmount: 0.0, //返利池总金额
      rebateTotalAmount: 0.0, //返利池使用总金额
      // totalFuelAmount:0,//账户总金额
    };
  },
  components: {
    addCar,
    DiscountDetail,
  },
  created() {
    this.getAmountDetail(this.dealerCode);
    console.log(this.isClientOrder, '=======================');
  },
  mounted() {
    this.table = this.$refs.table.$refs.pageTable;
  },
  mixins: [dictionary],
  methods: {
    // reComputedRebateAndAmount() {
    //   this.realPayTotalAmount = 0;
    //   this.rebateTotalAmount = 0;
    //   this.tableList.forEach((data) => {
    //     if (data.orderNum === '') {
    //       this.formList.find((item) => item.fieldName === 'realPayTotalAmount').initialValue = this.realPayTotalAmount;
    //       this.formList.find((item) => item.fieldName === 'rebateTotalAmount').initialValue = this.rebateTotalAmount;
    //       return;
    //     }
    //     //使用返利
    //     let num = Number(data.orderNum);
    //     if (data.isRebate == 10041001) {
    //       //可以使用的台数
    //       let x = Math.floor((this.singleRebateFuelAmount - this.rebateTotalAmount) / data.singleRebate);
    //       if (num < x) {
    //         this.rebateTotalAmount += num * data.singleRebate;
    //         this.realPayTotalAmount += num * data.directivePrice;
    //         //单条数据总金额
    //         data.rebateTotalAmount = num * data.singleRebate;
    //         this.realPayTotalAmount = this.realPayTotalAmount - this.rebateTotalAmount < 0 ? 0 : this.realPayTotalAmount - this.rebateTotalAmount;
    //         this.formList.find((item) => item.fieldName === 'realPayTotalAmount').initialValue = this.realPayTotalAmount;
    //         this.formList.find((item) => item.fieldName === 'rebateTotalAmount').initialValue = this.rebateTotalAmount;
    //       } else {
    //         this.rebateTotalAmount += x * data.singleRebate;
    //         this.realPayTotalAmount += num * data.directivePrice;
    //         //单条数据总金额
    //         data.rebateTotalAmount = x * data.singleRebate;
    //         this.realPayTotalAmount = this.realPayTotalAmount - this.rebateTotalAmount < 0 ? 0 : this.realPayTotalAmount - this.rebateTotalAmount;
    //         this.formList.find((item) => item.fieldName === 'realPayTotalAmount').initialValue = this.realPayTotalAmount;
    //         this.formList.find((item) => item.fieldName === 'rebateTotalAmount').initialValue = this.rebateTotalAmount;
    //       }
    //     } else {
    //       this.realPayTotalAmount += num * data.directivePrice;
    //       this.formList.find((item) => item.fieldName === 'realPayTotalAmount').initialValue = this.realPayTotalAmount;
    //     }
    //   });
    // },
    //地址选择
    initCityLink(value) {
      this.formList[9].initialValue = '';
      this.formList[11].initialValue = '';
      this.formList[10].initialValue = '';
      for (let i in this.addressDTO) {
        if (this.addressDTO[i].addressId === value) {
          this.formList[9].initialValue = this.addressDTO[i].cityName;
          this.formList[10].initialValue = this.addressDTO[i].linkMan;
          this.formList[11].initialValue = this.addressDTO[i].linkPhone;
          return;
        }
      }
    },
    changeValueNum(a) {
      if (!a || a == null || isNaN(a)) {
        return 0;
      } else {
        return a;
      }
    },
    // 新增车辆
    addHandle() {
      // this.$refs.from.SUBMIT_FORM();
      // if (this.saveData) {
      //   let json = JSON.parse(JSON.stringify(this.saveData));
      // json.dealerCode = this.dealerCode;
      // this.rowData = json;
      this.isaddCar = true;
      // this.saveData = null;
      // }
    },
    async changeFrom() {
      if (this.tableList.length < 1) {
        return;
      }
    },
    changeHandle(val) {
      this.saveData = val;
    },
    //删除
    changeList(list) {
      // this.resetCache(); //重置余额池
      // this.tableList.map((x) => {
      //   this.reComputedTable(x);
      // });
      // this.reComputedForm();
    },
    //获取总金额和返利和地址
    async getAmountDetail(code) {
      let res = await getAmount({ dealerCode: code });
      this.addressDTO = res.data.addressDTOS;
      this.addressDTO.map((x) => {
        this.formList.find((item) => item.fieldName === 'addressId').itemList.push({ text: x.address, value: x.addressId });
      });
      //todo 地址待修改
      this.formList.find((item) => item.fieldName === 'addressId').initialValue = this.formList.find((item) => item.fieldName === 'addressId').itemList[1].value;
      this.initCityLink(this.formList.find((item) => item.fieldName === 'addressId').initialValue);

      for (let i in res.data) {
        this.formList.map((x) => {
          if (x.fieldName == i) {
            x.initialValue = res.data[i];
          }
          //初始化账户总金额,返利池金额
          if (x.fieldName == 'totalFuelAmount') {
            this.totalFuelAmount = res.data['totalFuelAmount'];
          }
          if (x.fieldName == 'singleRebateFuelAmount') {
            this.singleRebateFuelAmount = res.data['singleRebateFuelAmount'];
          }
        });
      }
    },

    async closeDrawer(type) {
      if (type == 1) {
        this.$emit('close');
      } else if (type == 2) {
        if (this.tableList.length < 1) {
          this.$notify({
            title: '警告',
            message: '请选择车辆',
            type: 'warning',
          });
          return;
        }

        this.table.GET_REQUIRED_ERROR();
        let json = this.$refs.from.SUBMIT_FORM();
        for (let i in this.addressDTO) {
          if (this.addressDTO[i].addressId === json.addressId) {
            json.address = this.addressDTO[i].address;
            break;
          }
        }
        let arr = this.tableList;
        let is = false;
        arr.map((x) => {
          if (x.orderNum === '') {
            this.$notify({
              title: '警告',
              message: '提报数量不允许为空',
              type: 'warning',
            });
            is = true;
            return;
          }
          if (Number(x.orderNum) > 10000000000 || Number(x.orderNum) < 1) {
            this.$notify({
              title: '警告',
              message: '输入数量过大或过小',
              type: 'warning',
            });
            is = true;
            return;
          }
          x.oemDirectivePrice = this.formatNumber(this.changeValueNum(x.oemDirectivePrice));
        });
        if (is) {
          return;
        }
        json.detailDTOList = arr;
        json.orderStatus = 24081002;
        this.exportLoading = true;
        let res = await saveOrder(json);
        if (res.resultCode == 200) {
          this.exportLoading = false;
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
          });
          this.$emit('close', json);
        } else {
          this.exportLoading = false;
          this.saveData = null;
        }
      } else if (type == 3) {
        //3

        if (this.tableList.length < 1) {
          this.$notify({
            title: '警告',
            message: '请选择车辆',
            type: 'warning',
          });
          return;
        }
        this.table.GET_REQUIRED_ERROR();
        let json = this.$refs.from.SUBMIT_FORM();
        for (let i in this.addressDTO) {
          if (this.addressDTO[i].addressId === json.addressId) {
            json.address = this.addressDTO[i].address;
            break;
          }
        }
        let arr = this.tableList;
        let is = false;
        arr.map((x) => {
          if (x.orderNum === '') {
            this.$notify({
              title: '警告',
              message: '提报数量不允许为空',
              type: 'warning',
            });
            is = true;
            return;
          }
          if (Number(x.orderNum) > 10000000000 || Number(x.orderNum) < 1) {
            this.$notify({
              title: '警告',
              message: '输入数量过大或过小',
              type: 'warning',
            });
            is = true;
            return;
          }

          if (x.targetType === 24031002 && Number(x.orderNum) > Number(x.targetNum)) {
            this.$notify.warning({ title: '提示信息', message: '配额提报数量大于月度指标配额数量' });
            is = true;
            return;
          }
          x.oemDirectivePrice = this.formatNumber(this.changeValueNum(x.oemDirectivePrice));

        });
        if (is) {
          return;
        }
        json.detailDTOList = arr;
        this.exportLoading = true;
        let res = await saveOrder(json);
        if (res.resultCode == 200) {
          this.exportLoading = false;
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
          });
          this.$emit('close', json);
        } else {
          this.exportLoading = false;
          this.saveData = null;
        }
      }
    },

    carcloseHandler(type, data) {
      // if (data) {
      //   let is = false;
      //   this.tableList.map((x) => {
      //     data.forEach((e) => {
      //       if (x.productCode == e.productCode) {
      //         is = true;
      //       }
      //     });
      //   });
      //   if (!is) {
      this.isaddCar = type;
      this.isDisabled = false;
      this.table.EXECUTE_INSERT(data);
      // } else {
      //   // 提示
      //   this.$notify({
      //     title: '警告',
      //     message: '列表已有该车辆',
      //     type: 'warning',
      //   });
      // }
      // }
    },
    Discountclose() {
      this.isDiscount = false;
    },

    //改变首尾计算规则
    buildRebateTypeChange() {
      this.resetCache();
      this.tableList.map((x) => {
        this.reComputedTable(x);
      });
      this.reComputedForm();
    },
    //改变数量
    changeNum(index, data) {
      console.log(index, data, '改变数量');
      // this.reComputedRebateAndAmount();
      let num = '';
      let str = '';
      for (let i in index) {
        num = index[i];
        str = i.split('|')[0];
      }
      let Rep = /^[1-9]\d*$/;
      if (num > 10000000000) {
        this.$notify({
          title: '警告',
          message: '输入数量过大',
          type: 'warning',
        });
        return;
      }
      if (Rep.test(num)) {
        //todo 订单中紧急的订单不能超过比例
        // this.reComputedRebateAndAmount();
      }
    },
    async editHandle(data, type) {
      if (type == 1) {
        await this.$confirm('是否确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            this.table.EXECUTE_DELETE([data]);
            this.changeList(this.tableList);
          })
          .catch(() => {});
      } else {
        this.DiscountData = data;
        this.isDiscount = true;
      }
    },
    formatNumber(val) {
      return Number(val).toFixed(2);
    },

    createdFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '订单信息',
        },

        {
          type: 'INPUT',
          label: '订货单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearMonth',
          disabled: true,
          placeholder: '请输入',
          dateType: 'month',
          initialValue: moment().format('YYYY-MM'),
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          placeholder: '请选择',
          itemList: this.createDictList('2410'),
          initialValue: 24101002,
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('2408'),
          initialValue: 24081001,
        },
        {
          type: 'SELECT',
          label: '订单紧急度',
          fieldName: 'emergencyType',
          placeholder: '请选择',
          itemList: this.createDictList('2101'),
          initialValue: 21011001,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          change: (p) => {
            this.changeFrom();
          },
        },
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'transportType',
          placeholder: '请选择',
          itemList: this.createDictList('2409'),
          initialValue: 24091001,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          change: (p) => {
            this.changeFrom();
          },
        },
        {
          type: 'SELECT',
          label: '收车地址',
          selfCols: '2',
          fieldName: 'addressId',
          placeholder: '请选择',
          itemList: [],
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          change: (value) => {
            this.initCityLink(value);
          },
        },
        {
          type: 'INPUT',
          label: '送达城市',
          fieldName: 'cityName',
          placeholder: '请选择',
          // initialValue: 60041001,
          // itemList: [],
          disabled: true,
          // rules: [{ required: true, message: '请选择', trigger: 'change' }],
          // change: p => {
          //   this.changeFrom();
          // }
        },

        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'linkMan',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '联系电话',
          fieldName: 'linkPhone',
          disabled: true,
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          initialValue: 0.0,
          label: '资金总余额',
          fieldName: 'totalFuelAmount',
          placeholder: '请选择',
          disabled: true,
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '返利池可用余额',
          fieldName: 'singleRebateFuelAmount',
          placeholder: '请选择',
          initialValue: 0.0,
          disabled: true,
        },
        // {
        //   type: 'INPUT_NUMBER',
        //   precision: 2,
        //   label: '返利池使用总金额',
        //   fieldName: 'rebateTotalAmount',
        //   placeholder: '请选择',
        //   initialValue: 0.0,
        //   disabled: true,
        // },
        // {
        //   type: 'INPUT_NUMBER',
        //   label: '实付总金额',
        //   fieldName: 'realPayTotalAmount',
        //   precision: 2,
        //   initialValue: 0.0,
        //   disabled: true,
        // },
        {
          type: 'INPUT',
          label: '创建人',
          fieldName: 'createdBy',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '创建时间',
          fieldName: 'createdAt',
          disabled: true,
        },
        {
          type: 'BREAK_SPACE',
          label: '车辆信息',
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 120,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 1)}>
                  删除
                </multiuse-button>
              </div>
            );
          },
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          width: 200,
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          align: 'center',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '指标类型',
          dataIndex: 'targetType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (props) => {
            return <span>{this.createDictText(props.row.targetType, '2403')}</span>;
          },
        },
        {
          title: '提报数量',
          dataIndex: 'orderNum',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'number',
          width: 100,
          editRequired: true,
          editPattern: /^[1-9]\d*$/,
          summation: true,
          defaultEditable: true,
          rules: [{ required: true, message: '请填写正整数', trigger: 'blur' }],
          onInput: (index, data) => {
            this.changeNum(index, data);
          },
        },
        {
          title: '车辆用途',
          dataIndex: 'vehicleUse',
          width: 180,
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'number',
          editRequired: true,
          rules: [{ required: true, message: '请填写正整数', trigger: 'blur' }],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.vehicleUse}
                placeholder="请选择"
                onChange={(value) => {
                  p.row.vehicleUse = value;
                }}
              >
                {p.row.vehicleUserList.map((item) => (
                  <el-option key={item.value} label={item.text} value={item.value} />
                ))}
              </el-select>
            );
          },
        },
        {
          title: '资金类型',
          dataIndex: 'accountId',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'number',
          editRequired: true,
          rules: [{ required: true, message: '请填写正整数', trigger: 'blur' }],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.accountId}
                required
                placeholder="请选择"
                onChange={(value) => {
                  p.row.accountId = value;
                }}
              >
                {p.row.accountTypes.map((item) => (
                  <el-option key={item.accountId} label={item.accountTypeName} value={item.accountId} />
                ))}
              </el-select>
            );
          },
        },
        // {
        //   title: '结算价格',
        //   dataIndex: 'directivePrice',
        //   precision: 2,
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        // },
        {
          title: '市场指导价',
          dataIndex: 'oemDirectivePrice',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        // {
        //   title: '折扣',
        //   dataIndex: 'discountAmount',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   precision: 2,
        //   render: (p) => {
        //     return (
        //       <span class="discount" onClick={() => this.editHandle(p.row, 2)}>
        //         {p.row.discountAmount}
        //       </span>
        //     );
        //   },
        // },
        // {
        //   title: '促销2',
        //   dataIndex: 'cuxiao2',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '促销3',
        //   dataIndex: 'cuxiao3',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '促销4',
        //   dataIndex: 'cuxiao4',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '是否使用返利',
        //   dataIndex: 'isRebate',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   render: (p) => {
        //     return (
        //       <el-select
        //         size="mini"
        //         v-model={p.row.isRebate}
        //         placeholder="请选择"
        //         onChange={(value) => {
        //           p.row.isRebate = value;
        //         }}
        //       >
        //         {this.createDictList('1004').map((item) => (
        //           <el-option key={item.value} label={item.text} value={item.value} />
        //         ))}
        //       </el-select>
        //     );
        //   },
        // },
        // {
        //   title: '返利金额',
        //   dataIndex: 'singleRebateAmount',
        //   sorter: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'input',
        // },
        {
          title: '车系名称',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配置名称',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '选装名称',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '内饰',
          dataIndex: 'trimColorName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
      ];
    },
  },
};
</script>
<style lang="less">
.discount {
  text-decoration: underline;
  color: #d1291a;
  cursor: pointer;
}
</style>
